package com.flyketch.demo.config;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 专门用来处理 WebSocket 的
 * created by flyketch
 * 20-1-2 下午7:08
 */
@Component
public class ChatHandler extends TextWebSocketHandler {


    public static ConcurrentHashMap<String, Set<WebSocketSession>> roomUserMap = new ConcurrentHashMap<>();

    // 1. websocket --- 客户端连接建立过程

    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        UriComponents uriComponents = UriComponentsBuilder.fromUri(session.getUri()).build();
        String roomId = uriComponents.getQueryParams().getFirst("roomId");

        // 保存session
        String key = "room: " + roomId;
        roomUserMap.putIfAbsent(key, new HashSet<>()); // 如果没有值则插入
        roomUserMap.get(key).add(session);

        System.out.println("新用户来了： " + session);
    }


    // 2. 数据交互 --- 客户端发送数据到服务端

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        // ...
        System.out.println("数据交互 session is " + session + "message is " + message);

        // 收到消息广播给所有人
        UriComponents uriComponents = UriComponentsBuilder.fromUri(session.getUri()).build();
        String roomId = uriComponents.getQueryParams().getFirst("roomId");
        String userId = uriComponents.getQueryParams().getFirst("userId");
        String key = "room: " + roomId;

        broadcastMessage(key, message.getPayload());
    }

    // 3. 连接关闭/断开 --- 退出房间

    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        UriComponents uriComponents = UriComponentsBuilder.fromUri(session.getUri()).build();
        String roomId = uriComponents.getQueryParams().getFirst("roomId");

        // 保存session
        String key = "room: " + roomId;
        roomUserMap.putIfAbsent(key, new HashSet<>()); // 如果没有值则插入
        roomUserMap.get(key).remove(session);
        System.out.println("用户退出了房间： " + session);
    }


    // 4. 推送其他人发送的消息到用户客户端上面
    private void broadcastMessage(String key, String message) throws IOException {
        Set<WebSocketSession> webSocketSessions = roomUserMap.get(key);
        for (WebSocketSession webSocketSession : webSocketSessions) {
            webSocketSession.sendMessage(new TextMessage(message));
        }
    }

}